import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'app_strings.dart';
import 'network/http_manager.dart';
import 'network/request_api.dart';
import 'network/response.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void _login() {
    HttpManager.getInstance().get(RequestApi.login()).then((resp) async {
      var data = jsonDecode(resp);
      LoginResp loginResp = LoginResp.fromJson(data);

      SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();
      await sharedPreferences.setString(
          AppStrings.SP_KEY_TOKEN, loginResp.token);

      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text("登录成功"),
      ));
    });
  }

  void _queryData() {
    HttpManager.getInstance().get(RequestApi.queryData()).then((resp) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(resp),
      ));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(
                onPressed: _login,
                child: Text(
                  '登录',
                )),
            TextButton(
                onPressed: _queryData,
                child: Text(
                  '登录后操作',
                ))
          ],
        ),
      ),
    );
  }
}
